#!/usr/bin/env python2
#-*- coding: utf-8 -*-

import traceback


from Ump import utils, defs

from Ump.common import log
from Ump.common import exception
from Ump.common import config

from Ump.objs.db import models
from Ump.objs.session_wrapper import enable_log_and_session
from Ump.objs.manager_base import Manager


LOG = log.get_log('Ump.objs.snapshot.manager')


class SnmpManager(Manager):

    def __init__(self):
        self.super_ = super(SnmpManager, self).__init__()

    @enable_log_and_session(resource='snmp', event='add')
    def set_snmp_host(self, _logger, kwargs):

        snmp_host = kwargs.get('snmp_host')

        _logger.update_props(oplog_obj=snmp_host)

        if not snmp_host:
            raise Exception('snmp_host is null')

        snmp_hosts = self._get_snmp_hosts()
        snmp_hosts.append(snmp_host) 
        snmp_hosts = list(set(snmp_hosts))
        
        self._write_snmp_host(snmp_hosts)

    def _write_snmp_host(self, snmp_hosts):
        snmp_hosts = [x for x in snmp_hosts if x]
        config_snmp_host = ",".join(snmp_hosts)

        config.cp.set('ump_main', 'snmp_host', config_snmp_host)
        with open(defs.CONFIG_PATH, 'w') as configfile:
            config.cp.write(configfile)

    def _get_snmp_hosts(self):
        reload(config)
        snmp_hosts =  config.snmp_host
        return snmp_hosts

    @enable_log_and_session(resource='snmp', event='delete')
    def delete(self, _logger, kwargs):
        snmp_host = kwargs.get('snmp_host')

        _logger.update_props(oplog_obj=snmp_host)
        
        snmp_hosts = self._get_snmp_hosts()
        snmp_hosts = list(set(snmp_hosts))
        if snmp_host in snmp_hosts:
            snmp_hosts.remove(snmp_host) 

        self._write_snmp_host(snmp_hosts)

    @enable_log_and_session(resource='snmp', event='add', disable_oplog=True)
    def get_snmp_hosts(self, _logger, kwargs):
        reload(config)
        snmp_hosts =  config.snmp_host
        return snmp_hosts
        
    @enable_log_and_session(resource='snmp', event='send')
    def send_test(self, _logger, kwargs):     
        snmp_host = kwargs.get('snmp_host')

        _logger.update_props(oplog_obj=snmp_host)
        
        prefix = 'snmptrap -v 2c -c public %s:162 "" LICH-MIB::trapEvent SNMPv2-MIB::sysLocation.0 s "%s"'
        msg = "This is a test message sent by FusionStor"
        snmp_cmd =  prefix % (snmp_host, msg)
        recode, stdout, stderr = utils._exec_pipe(snmp_cmd)
        
        if recode != 0:
            raise Exception('发送测试消息失败, %s:%s' % (recode, stderr))
        
